package com.ayu.wxgzh.ayucyy.Utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.ocr_api20210707.Client;
import com.aliyun.ocr_api20210707.models.RecognizeGeneralRequest;
import com.aliyun.ocr_api20210707.models.RecognizeGeneralResponse;
import com.aliyun.teaopenapi.models.Config;

/**
 * 通用文字识别（阿里云）
 */
public class RecognizeCharacterUtil {

    // AccessKey ID
    private static final String accessKeyId = "LTAI5tMxcEsSoeEiRHKg4xYJ";

    // AccessKey Secret
    private static final String accessKeySecret = "WdSkxvhNjXZHvM7bpcU1V6lECRT2YN";

    /**
     * 使用AK&SK初始化账号Client
     *
     * @param accessKeyId
     * @param accessKeySecret
     * @return Client
     * @throws Exception
     */
    public static Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
        Config config = new Config()
                // 您的AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 您的AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // 访问的域名
        config.endpoint = "ocr-api.cn-hangzhou.aliyuncs.com";
        return new Client(config);
    }

    /**
     * 上传图片地址，识别图片中的文字
     *
     * @param url
     * @return
     * @throws Exception
     */
    public static String RecognizeCharacter(String url) throws Exception {
        Client client = createClient(accessKeyId, accessKeySecret);
        RecognizeGeneralRequest request = new RecognizeGeneralRequest();
        request.setUrl(url);
        RecognizeGeneralResponse response = client.recognizeGeneral(request);
        String data = response.getBody().getData();
        JSONObject jsonObject = JSON.parseObject(data);
        return jsonObject.getString("content");
    }

}

